<template>
  <div class="posts-page">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <h2>我发布的动态</h2>
          <el-button type="primary" @click="createPost">
            <el-icon><Plus /></el-icon>
            发布动态
          </el-button>
        </div>
      </template>

      <!-- 筛选栏 -->
      <div class="filter-bar mb-4">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索动态"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="filterType"
          placeholder="动态类型"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="图文" value="image" />
          <el-option label="视频" value="video" />
        </el-select>

        <el-select
          v-model="filterStatus"
          placeholder="动态状态"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="已发布" value="published" />
          <el-option label="待审核" value="pending" />
          <el-option label="已隐藏" value="hidden" />
        </el-select>

        <el-select
          v-model="sortBy"
          placeholder="排序方式"
          @change="handleSortChange"
        >
          <el-option label="最新发布" value="latest" />
          <el-option label="最多点赞" value="likes" />
          <el-option label="最多评论" value="comments" />
        </el-select>
      </div>

      <!-- 动态列表 -->
      <div class="posts-list" v-loading="loading">
        <div v-for="post in postsList" :key="post.id" class="post-item">
          <div class="post-header">
            <div class="post-info">
              <el-tag size="small" :type="getTagType(post.status)" class="mr-2">
                {{ getStatusText(post.status) }}
              </el-tag>
              <el-tag size="small" type="info" class="mr-2">
                {{ getTypeText(post.type) }}
              </el-tag>
              <span class="post-time">{{ formatDate(post.createTime) }}</span>
            </div>
            <div class="post-actions">
              <el-button-group>
                <el-button type="primary" link @click="editPost(post)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button type="danger" link @click="deletePost(post)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </el-button-group>
            </div>
          </div>

          <div class="post-content">{{ post.content }}</div>

          <!-- 图片列表 -->
          <div
            v-if="post.type === 'image' && post.images?.length"
            class="post-images"
          >
            <el-image
              v-for="(image, index) in post.images"
              :key="index"
              :src="image"
              :preview-src-list="post.images"
              fit="cover"
              class="post-image"
            />
          </div>

          <!-- 视频播放器 -->
          <div v-if="post.type === 'video' && post.video" class="post-video">
            <video :src="post.video" controls class="video-player" />
          </div>

          <div class="post-meta">
            <div class="meta-item">
              <el-icon><View /></el-icon>
              <span>{{ post.viewCount }} 次浏览</span>
            </div>
            <div class="meta-item">
              <el-icon><ThumbUp /></el-icon>
              <span>{{ post.likeCount }} 次点赞</span>
            </div>
            <div class="meta-item">
              <el-icon><ChatDotRound /></el-icon>
              <span>{{ post.commentCount }} 条评论</span>
            </div>
            <div class="meta-item">
              <el-icon><Share /></el-icon>
              <span>{{ post.shareCount }} 次分享</span>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && postsList.length === 0"
          description="暂无动态"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Search,
  View,
  ThumbUp,
  ChatDotRound,
  Share,
  Edit,
  Delete,
} from "@element-plus/icons-vue";

const router = useRouter();

// 状态变量
const loading = ref(false);
const searchKeyword = ref("");
const filterType = ref("");
const filterStatus = ref("");
const sortBy = ref("latest");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 动态列表数据
const postsList = ref([
  {
    id: 1,
    content: "今天在贵港江滨公园拍到的美景，分享给大家！",
    type: "image",
    status: "published",
    images: [
      "/images/posts/park1.jpg",
      "/images/posts/park2.jpg",
      "/images/posts/park3.jpg",
    ],
    createTime: "2024-03-20 10:00:00",
    viewCount: 128,
    likeCount: 32,
    commentCount: 8,
    shareCount: 4,
  },
  {
    id: 2,
    content: "记录贵港美食文化，带你探索地道小吃",
    type: "video",
    status: "published",
    video: "/videos/food-culture.mp4",
    createTime: "2024-03-19 15:30:00",
    viewCount: 256,
    likeCount: 64,
    commentCount: 16,
    shareCount: 8,
  },
]);

// 获取动态列表
const getPostsList = async () => {
  loading.value = true;
  try {
    // TODO: 调用获取动态列表API
    // const { data } = await api.getPostsList({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   keyword: searchKeyword.value,
    //   type: filterType.value,
    //   status: filterStatus.value,
    //   sortBy: sortBy.value
    // })
    // postsList.value = data.list
    // total.value = data.total
  } catch (error) {
    console.error("获取动态列表失败:", error);
    ElMessage.error("获取动态列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getPostsList();
};

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1;
  getPostsList();
};

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1;
  getPostsList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  getPostsList();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  getPostsList();
};

// 创建动态
const createPost = () => {
  router.push("/community/post/create");
};

// 编辑动态
const editPost = (post) => {
  router.push(`/community/post/edit/${post.id}`);
};

// 删除动态
const deletePost = async (post) => {
  try {
    await ElMessageBox.confirm("确定要删除该动态吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // TODO: 调用删除动态API
    // await api.deletePost(post.id)
    ElMessage.success("删除成功");
    getPostsList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除动态失败:", error);
      ElMessage.error("删除动态失败");
    }
  }
};

// 获取状态标签类型
const getTagType = (status) => {
  const typeMap = {
    published: "success",
    pending: "warning",
    hidden: "info",
  };
  return typeMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    published: "已发布",
    pending: "待审核",
    hidden: "已隐藏",
  };
  return textMap[status] || "未知";
};

// 获取类型文本
const getTypeText = (type) => {
  const textMap = {
    image: "图文",
    video: "视频",
  };
  return textMap[type] || "其他";
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

onMounted(() => {
  getPostsList();
});
</script>

<style lang="scss" scoped>
.posts-page {
  .page-card {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm;

    :deep(.el-card__header) {
      @apply p-0 border-b border-gray-100 dark:border-gray-700;

      .card-header {
        @apply px-6 py-4 flex items-center justify-between;

        h2 {
          @apply text-lg font-medium text-gray-900 dark:text-white;
        }
      }
    }
  }

  .filter-bar {
    @apply flex items-center gap-4;

    .search-input {
      @apply w-64;
    }
  }

  .posts-list {
    @apply space-y-4;

    .post-item {
      @apply p-4 bg-gray-50 dark:bg-gray-800 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-300;

      .post-header {
        @apply flex items-center justify-between mb-3;

        .post-info {
          @apply flex items-center;

          .post-time {
            @apply text-sm text-gray-500 dark:text-gray-400;
          }
        }
      }

      .post-content {
        @apply text-gray-900 dark:text-white mb-4 whitespace-pre-wrap;
      }

      .post-images {
        @apply grid grid-cols-3 gap-2 mb-4;

        .post-image {
          @apply w-full h-32 rounded-lg object-cover cursor-pointer transition-transform duration-300;

          &:hover {
            @apply transform scale-105;
          }
        }
      }

      .post-video {
        @apply mb-4;

        .video-player {
          @apply w-full rounded-lg;
          max-height: 400px;
        }
      }

      .post-meta {
        @apply flex items-center gap-6;

        .meta-item {
          @apply flex items-center text-sm text-gray-500 dark:text-gray-400;

          .el-icon {
            @apply mr-1;
          }
        }
      }
    }
  }

  .pagination-wrapper {
    @apply flex justify-center mt-6;
  }
}
</style>
